package controllers;

import com.avaje.ebean.Ebean;
import com.avaje.ebean.Page;
import models.CustomerInformation;
import models.production.TaskSpec;
import models.Product;
import play.data.Form;
import play.mvc.Controller;
import play.mvc.Result;
import views.html.Product.create;
import views.html.Product.list;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Huyen
 * Date: 4/21/12
 * Time: 2:38 PM
 * To change this template use File | Settings | File Templates.
 */
public class ProductController extends Controller {
    public static Result GO_HOME = redirect(
            routes.ProductController.list(0, "name", "asc", "")
    );

    public static Result index() {
        return GO_HOME;
    }

    public static Result create() {
        Form<Product> computerForm = form(Product.class);
        List<TaskSpec> allProcessTask = TaskSpec.find.all();
        List<CustomerInformation> allCustomer = CustomerInformation.all();

        return ok(
                create.render(computerForm, allProcessTask, allCustomer)
        );
    }

    public static Result save() {
        Form<Product> productForm = form(Product.class).bindFromRequest();
        if (productForm.hasErrors()) {
            List<TaskSpec> allProcessTask = TaskSpec.find.all();
            List<CustomerInformation> allCustomer = CustomerInformation.all();
            return badRequest(create.render(productForm, allProcessTask, allCustomer));
        }
        productForm.get().save();
        flash("success", "Sản phẩm " + productForm.get().name + " đã được thêm mới");
        return GO_HOME;
    }

    public static Result list(int page, String sortBy, String order, String filter) {
        Page<Product> first = Product.page(page, 10, sortBy, order, filter);

        return ok(list.render(first, sortBy, order, filter));
    }

    public static Result initData() {
        List<Product> products = new ArrayList<Product>();
        for (int i = 0; i < 20; i++) {
            Product product = new Product();
            product.code = "code" + i;
            product.name = "Sản phẩm " + i;
            product.customer = "Khách hàng" + i;
            products.add(product);
        }
        Ebean.beginTransaction();
        Ebean.save(products);
        Ebean.commitTransaction();
        flash("success", "Hoàn thành cập nhật dữ liệu sản phẩm");
        return GO_HOME;
    }
}
